//评论功能

package com.wzy.wzyblog.web;

import com.wzy.wzyblog.po.Comment;
import com.wzy.wzyblog.po.User;
import com.wzy.wzyblog.service.BlogService;
import com.wzy.wzyblog.service.CommentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;

import javax.servlet.http.HttpSession;

@Controller
public class CommentController {

    @Autowired
    private CommentService commentService;

    @Autowired
    private BlogService blogService;

//      注入获取用户头像
    @Value("${comment.avatar}")
    private String avatar;

    //    获取blog下指定id的评论
    @GetMapping("/comments/{blogId}")
    public String comments(@PathVariable Long blogId, Model model){
        model.addAttribute("comments",commentService.listCommentByBlogId(blogId));
//        局部刷新 返回blog页面下的commentlist片段
        return "blog::commentList";
    }

//    接收到发布按钮的信息
    @PostMapping("/comments")
    public String post(Comment comment, HttpSession session) {
//        根据blog的id获取对象
        Long blogId = comment.getBlog().getId();
//              保存         根据blogId查询到的对象
        comment.setBlog(blogService.getBlog(blogId));
//        获取管理员用户
        User user = (User) session.getAttribute("user");
//        管理员用户不为空
        if (user != null) {
//            获取管理员头像
            comment.setAvatar(user.getAvatar());
//            管理员 博主标记
            comment.setAdminComment(true);
        } else {
//            获取用户头像
            comment.setAvatar(avatar);
        }
//        保存
        commentService.saveComment(comment);
//        局部返回到评论区域     获取blog对象的id
        return "redirect:/comments/"+blogId;
    }
}
